// pages/blueconn/blueconn.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    services: [],
    serviceId: 0,
    writeCharacter: false,
    readCharacter: false,
    notifyCharacter: false,
    isScanning:false
  },


  /**
   * 蓝牙初始化，检查是否已经开启蓝牙
   */ 
  startSearch: function () {
    var that = this
    wx.openBluetoothAdapter({
      success: function (res) {
        wx.getBluetoothAdapterState({
          success: function (res) {
            if (res.available) {
              if (res.discovering) {
                wx.stopBluetoothDevicesDiscovery({
                  success: function (res) {
                    console.log(res)
                  }
                })
              }
              that.checkPemission()
            } else {
              wx.showModal({
                title: '提示',
                content: '本机蓝牙不可用',
              })
            }
          },
        })
      }, fail: function () {
        wx.showModal({
          title: '提示',
          content: '蓝牙初始化失败，请打开蓝牙',
        })
      }
    })
  },

  /**
   * 区分平台开放蓝牙权限
   */
  checkPemission: function () {  //android 6.0以上需授权地理位置权限
    var that = this
    var platform = app.BLEInformation.platform
    if (platform == "ios") {
      app.globalData.platform = "ios"
      that.getBluetoothDevices()
    } else if (platform == "android") {
      app.globalData.platform = "android"
      console.log(app.getSystem()) //这里是拿到安卓的系统版本名 如：Android 9
      console.log('输出系统版本号',app.getSystem().substring(app.getSystem().length - (app.getSystem().length - 8), app.getSystem().length - (app.getSystem().length - 8) + 1)) //这里为了获取到系统的版本号，如 9
      var systemVersion = app.getSystem().substring(app.getSystem().length - (app.getSystem().length - 8), app.getSystem().length - (app.getSystem().length - 8) + 1)
      if (systemVersion > 5) {
        wx.getSetting({
          success: function (res) {
            console.log(res) //
            if (!res.authSetting['scope.userLocation']) {
              wx.authorize({
                scope: 'scope.userLocation',
                complete: function (res) {
                  that.getBluetoothDevices()
                }
              })
            } else {
              that.getBluetoothDevices()
            }
          }
        })
      }
    }
  },

  /**
   * 获取蓝牙设备列表
   */
  getBluetoothDevices: function () {  
    var that = this
    console.log("开始查找可被使用发现的蓝牙设备")
    wx.showLoading({
      title: '获取蓝牙设备中',
    })
    that.setData({
      isScanning:true
    })
    wx.startBluetoothDevicesDiscovery({
      success: function (res) {
        console.log(res) //输出蓝牙设备列表查找的结果，是否成功
        setTimeout(function () {  //三秒后进行蓝牙设备的获取
          wx.getBluetoothDevices({
            success: function (res) {
              console.log(res)
              var devices = []
              var num = 0
              for (var i = 0; i < res.devices.length; ++i) {
                if (res.devices[i].name != "未知设备") { 
                  //筛选去除名字为未知设备的蓝牙设备
                  devices[num] = res.devices[i]
                  num++
                }
              }
              that.setData({
                list: devices,
                isScanning:false
              }) // 数据赋值 关闭刷新
              wx.hideLoading()
              wx.stopPullDownRefresh()
            },
          })
        }, 3000) //到这里 都是三秒后执行的内容
      },
    })
  },

  /**
   * 链接到某一个蓝牙设备上
  */
  bindViewTap: function (e) {
    var that = this
    wx.stopBluetoothDevicesDiscovery({ //关闭发现蓝牙设备
      success: function (res) { console.log(res) },
    })
    that.setData({
      serviceId: 0,
      writeCharacter: false,
      readCharacter: false,
      notifyCharacter: false
    })
    console.log("e",e)
    console.log(e.currentTarget.dataset.title)
    wx.showLoading({
      title: '正在建立连接',
    })
    // 与蓝牙设备建立链接
    wx.createBLEConnection({
      deviceId: e.currentTarget.dataset.title,
      success: function (res) {
        console.log('连接蓝牙设备成功',res)
        app.BLEInformation.deviceId = e.currentTarget.dataset.title
        that.getSeviceId() //获取服务ID
      }, fail: function (e) {
        wx.showModal({
          title: '提示',
          content: '连接失败',
        })
        console.log('蓝牙设备链接失败',e)
        wx.hideLoading()
      }, complete: function (e) {
        console.log(e)
      }
    })
  },

  getSeviceId: function () {
    var that = this
    var platform = app.BLEInformation.platform //获取平台信息
    console.log(app.BLEInformation.deviceId)   // 获取设备ID
    wx.getBLEDeviceServices({
      deviceId: app.BLEInformation.deviceId,
      success: function (res) {
        console.log(res)
        // 注释内容为方便调试特意直接赋值的一些信息，可以跳过
        var realId = ''
        if (platform == 'android') {
          // for(var i=0;i<res.services.length;++i){
          // var item = res.services[i].uuid
          // if (item == "0000FEE7-0000-1000-8000-00805F9B34FB"){
          realId = "0000FEE7-0000-1000-8000-00805F9B34FB"
          //       break;
          //     }
          // }
        } else if (platform == 'ios') {
          // for(var i=0;i<res.services.length;++i){
          // var item = res.services[i].uuid
          // if (item == "49535343-FE7D-4AE5-8FA9-9FAFD205E455"){
          realId = "49535343-FE7D-4AE5-8FA9-9FAFD205E455"
          // break
          // }
          // }
        }
        app.BLEInformation.serviceId = realId
        that.setData({
          services: res.services
        }) //将服务信息赋值到公共数据缓存
        that.getCharacteristics() //获取特征
      }, fail: function (e) {
        console.log(e)
      }, complete: function (e) {
        console.log(e)
      }
    })
  },

  /**
   * 获取特征信息
  */
  getCharacteristics: function () {
    var that = this
    var list = that.data.services
    var num = that.data.serviceId
    var write = that.data.writeCharacter
    var read = that.data.readCharacter
    var notify = that.data.notifyCharacter
    wx.getBLEDeviceCharacteristics({ //获取蓝牙设备的特征信息
      deviceId: app.BLEInformation.deviceId,
      serviceId: list[num].uuid,
      success: function (res) {
        console.log('获取特征成功的结果',res)
        for (var i = 0; i < res.characteristics.length; ++i) {
          var properties = res.characteristics[i].properties
          var item = res.characteristics[i].uuid
          if (!notify) {
            if (properties.notify) {
              app.BLEInformation.notifyCharaterId = item
              app.BLEInformation.notifyServiceId = list[num].uuid
              notify = true
            }
          }
          if (!write) {
            if (properties.write) {
              app.BLEInformation.writeCharaterId = item
              app.BLEInformation.writeServiceId = list[num].uuid
              write = true
            }
          }
          if (!read) {
            if (properties.read) {
              app.BLEInformation.readCharaterId = item
              app.BLEInformation.readServiceId = list[num].uuid
              read = true
            }
          }
        }
        if (!write || !notify || !read) {
          num++
          that.setData({
            writeCharacter: write,
            readCharacter: read,
            notifyCharacter: notify,
            serviceId: num
          })
         if(num == list.length){
           wx.showModal({
             title: '提示',
             content: '找不到该读写的特征值',
           })
         }else{
           that.getCharacteristics()
         }
        } else {
          that.openControl()
        }
      }, fail: function (e) {
        console.log(e)
      }, complete: function (e) {
        console.log("write:"+app.BLEInformation.writeCharaterId)
        console.log("read:"+app.BLEInformation.readCharaterId)
        console.log("notify:"+app.BLEInformation.notifyCharaterId)
      }
    })
  },

  /**
   * 跳转到给打印机发送信息的页面
  */
  openControl: function () {
    wx.navigateTo({
      url: '../sendCommand/sendCommand',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.BLEInformation.platform = app.getPlatform()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
      var that = this
      wx.startPullDownRefresh({})
      that.startSearch()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})